package cmd

import (
	"app/config"
	_ "app/internal"
	"app/internal/bootstrap"
	"context"
	"fmt"
	"github.com/spf13/cobra"
	"log"
	"net/http"
	"time"
)

func init() {
	rootCmd.AddCommand(httpCmd) //队列
}

var httpCmd = &cobra.Command{
	Use:   "http",
	Short: "start http work",
	Long:  `app http -c etc/config.yml`,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		//加载配置
		return config.LoadFromFile(configYml)
	},
	Run: func(cmd *cobra.Command, args []string) {
		log.Printf("【%s】服务启动中", cmd.Name())
		app := config.Config.App
		srv := &http.Server{
			Addr:    fmt.Sprintf("%s:%d", app.Host, app.Port),
			Handler: bootstrap.NewHttpRouter(app),
		}
		go func() {
			if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
				log.Fatalf("【%s】服务监听错误：%v", cmd.Name(), err)
			}
		}()

		waitForShutdown()

		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		if err := srv.Shutdown(ctx); err != nil {
			log.Printf("【%s】服务关闭错误：%v", cmd.Name(), err)
		}
		log.Printf("【%s】服务已经关闭", cmd.Name())
	},
	PostRunE: func(cmd *cobra.Command, args []string) error {
		return nil
	},
}
